/*
 * @Author: saber
 * @Date: 2021-11-02 15:54:34
 * @LastEditTime: 2021-11-02 16:17:10
 * @LastEditors: saber
 * @Description: 写token 和 删除 token 已经通过 token 来判断用户的的权限(是否登录)（疑惑 只用token就可以判断了吗，做的事情是否太多了）
 */

const ACCESSKEY = 'access-token';
let expire: number = 12 * 3600 * 100;
let key: string = ACCESSKEY;

const setExpire = (num: number) => {
  expire = num;
};

const getExpire = () => expire;

const setKey = (newKey: string) => (key = newKey);

const getKey = () => key || ACCESSKEY;
// 获取token
const getToken = () => {
  if (Date.now() - Number(localStorage.getItem(`${key}-expired`)) > 12 * 3600 * 1000) {
    delToken();
  }
  return localStorage.getItem(key);
};

const setToken = (token: string) => {
  // 设置token
  localStorage.setItem(key, token);
  // 设置 到期时间
  localStorage.setItem(`${key}-expired`, Date.now().toString());
};
// 删除token
const delToken = () => {
  localStorage.removeItem(key);
  localStorage.removeItem(`${key}-expired`);
};

export default {
  setExpire,
  getExpire,
  setKey,
  getKey,
  setToken,
  getToken,
  delToken,
  // 判断用户是否登录
  isValid: getToken,
  // 授权
  authorize: setToken,
  // 退出登录
  logout: delToken,
};
